package com.wtzz.police.base.util.component;

import com.wtzz.police.base.entity.User;
import com.wtzz.police.base.model.response.JwtAuthenticationResponse;
import com.wtzz.police.base.util.Constant;
import com.wtzz.police.base.util.WebTool;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -3301605591108950415L;

    public String getUsernameFromToken(String token) {
        String username;
        try {
            final Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(Constant.JWT_SECRET).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    public JwtAuthenticationResponse generateToken(UserDetails userDetails) {
        User user = (User) userDetails;
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, Constant.JWT_EXPIRATION);
        String ip = WebTool.getRequest().getRemoteAddr();
        String token = Jwts.builder().setSubject(user.getUsername()).setExpiration(cal.getTime()).claim(Constant.JWT_CLAIM_IP, ip)    //ip		客户IP
                           .signWith(SignatureAlgorithm.HS512, Constant.JWT_SECRET).compact();
        return new JwtAuthenticationResponse(token, cal.getTimeInMillis());
    }

    public JwtAuthenticationResponse refreshToken(String token) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, Constant.JWT_EXPIRATION);
        Claims claims = getClaimsFromToken(token);
        claims.setExpiration(cal.getTime());
        token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, Constant.JWT_SECRET).compact();
        return new JwtAuthenticationResponse(token, cal.getTimeInMillis());
    }

    public boolean validateToken(String token) {
        Claims claims = getClaimsFromToken(token);
        String ip = WebTool.getRequest().getRemoteAddr();
        if (token == null) {
            throw new RuntimeException("请从正常渠道登陆！");
        }
        String ip2 = (String) claims.get(Constant.JWT_CLAIM_IP);
        if (ip2 == null || !ip2.equals(ip)) {
            throw new RuntimeException("请从正常渠道登陆！");
        }
        return Boolean.TRUE;
    }

}